package com.retailshop.shopcontrol.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import com.retailshop.shopcontrol.common.ExcelUtil;
import com.retailshop.shopcontrol.common.MessageConstants;
import com.retailshop.shopcontrol.entity.HttpRequestConfig;
import com.retailshop.shopcontrol.entity.UploadFileConfig;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.file.Files;
import java.util.List;

@Controller
public class ExportController {
    @Autowired
    UploadFileConfig uploadFileConfig;

    @ResponseBody
    @RequestMapping(value = "/getDocuments", method = RequestMethod.POST)
    public void getDocuments(String path, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("path:" + path);
//        UserCommon.doExport(path,request,response);
        File tempFile = new File(path.trim());

        String fileName = tempFile.getName();
        //UserCommon.downLoadFromUrl(path,fileName,"/usr/local/mall_uploads/logistics",request,response);
    }
    @ResponseBody
    @RequestMapping(value = "/readExcel", method = RequestMethod.POST)
    public String readExcel(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
//            String url = "http://47.107.180.118:8083/wap/getUserNoInfo";
            String url = HttpRequestConfig.userServerUrl+"/wap/getUserNoInfo";
            //
        int n;
               File f = new File(file.getOriginalFilename());
        try ( InputStream in  = file.getInputStream(); OutputStream os = new FileOutputStream(f)){
            // 得到文件流。以文件流的方式输出到新文件
            // 可以使用byte[] ss = multipartFile.getBytes();代替while
            byte[] buffer = new byte[4096];
            while ((n = in.read(buffer,0,4096)) != -1){
                os.write(buffer,0,n);
            }
            // 读取文件第一行
            BufferedReader bufferedReader = new BufferedReader(new FileReader(f));
            System.out.println(bufferedReader.readLine());
            // 输出路径
            bufferedReader.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        //
//            InputStream is=request.getInputStream();

            FileInputStream fis=new FileInputStream(f);

            FileOutputStream fos=new FileOutputStream(file.getOriginalFilename());
            OutputStream os=response.getOutputStream();




//        System.out.println("pppppppppp");
//        List<String[]> list= ExcelUtil.readExcel(file);
//        System.out.println("list："+list.size());
//        int n;
//        // 得到MultipartFile文件
//        MultipartFile multipartFileS = file;
//        if(file==null){
//            System.out.println("空空空空空空空");
//        }
//        File f = null;
//        // 输出文件的新name 就是指上传后的文件名称
        //System.out.println("getName:"+file.getName());
//        // 输出源文件名称 就是指上传前的文件名称
        //System.out.println("Oriname:"+file.getOriginalFilename());
//        // 创建文件
//        f = new File(multipartFileS.getOriginalFilename());
//        try ( InputStream in  = multipartFileS.getInputStream(); OutputStream os = new FileOutputStream(f)){
//            // 得到文件流。以文件流的方式输出到新文件
//            // 可以使用byte[] ss = multipartFile.getBytes();代替while
//            byte[] buffer = new byte[4096];
//            while ((n = in.read(buffer,0,4096)) != -1){
//                os.write(buffer,0,n);
//            }
//            // 读取文件第一行
//            BufferedReader bufferedReader = new BufferedReader(new FileReader(f));
//            System.out.println(bufferedReader.readLine());
//            // 输出路径
//            bufferedReader.close();
//        }catch (IOException e){
//            e.printStackTrace();
//        }
//        // 输出file的URL
//        System.out.println(f.toURI().toURL().toString());
//        // 输出文件的绝对路径
//        System.out.println(f.getAbsolutePath());
//        // 操作完上的文件 需要删除在根目录下生成的文件
//        File fileT = new File(f.toURI());
//        if (fileT.delete()){
//            System.out.println("删除成功");
//        }else {
//            System.out.println("删除失败");
//
//        }
        //上传到七牛云
//        File fileQ = new File(f);
        //FileInputStream fileInputStream = new FileInputStream(f);
        //System.out.println("file----->" + file.getName());
//        MultipartFile multipartFileQ = new MockMultipartFile(zipUrl, file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
//        fileInputStream.close();
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        //获取流
//            byte[] uploadBytes = multipartFile.getBytes();
        byte[] uploadBytes = file.getBytes();
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = file.getOriginalFilename();
        Auth auth = Auth.create(uploadFileConfig.getAccessKey(), uploadFileConfig.getSecretKey());
        String upToken = auth.uploadToken(uploadFileConfig.getExportName());
        com.qiniu.http.Response responseLIU = uploadManager.put(uploadBytes, key, upToken);
        try {
            DefaultPutRet putRet = new Gson().fromJson(responseLIU.bodyString(), DefaultPutRet.class);
        }catch (QiniuException ex){
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }

        String filePath = uploadFileConfig.getExportUrl() + "/" + key;
//        url=filePath;
         //上传到七牛云

        return "";
    }
    public static MultipartFile getFile() throws IOException {
        String filePath = "F:\\test.txt";
        File file = new File(filePath);
        FileItem fileItem = new DiskFileItem("copyfile.txt", Files.probeContentType(file.toPath()),false,file.getName(),(int)file.length(),file.getParentFile());
        byte[] buffer = new byte[4096];
        int n;
        try (InputStream inputStream = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()){
            while ( (n = inputStream.read(buffer,0,4096)) != -1){
                os.write(buffer,0,n);
            }
            //也可以用IOUtils.copy(inputStream,os);
            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
            System.out.println(multipartFile.getName());
            return multipartFile;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    @ResponseBody
    @RequestMapping(value = "/getOrderUrl", method = RequestMethod.POST)
     public com.retailshop.shopcontrol.common.Response getOrderUrl(HttpServletRequest request){
        String urlS= HttpRequestConfig.orderServerUrl;
        //System.out.println("urls:"+urlS);
        HttpSession httpSession = request.getSession();
        String id = (String)httpSession.getAttribute("id");
        int intid=0;
        try {
            intid=Integer.parseInt(id);
        }catch (Exception e){}
        if(intid<=0){
            return new com.retailshop.shopcontrol.common.Response(MessageConstants.MSG_SYS_ERROR,urlS,intid,"",request);
        }else {
            return new com.retailshop.shopcontrol.common.Response(MessageConstants.MSG_SUCCESS,urlS,intid,"",request);
        }
     }
}
